package com.xaaef.grpc.client;

import cn.hutool.core.util.IdUtil;
import com.xaaef.grpc.lib.consts.GlobalConst;
import io.grpc.*;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.interceptor.GrpcGlobalClientInterceptor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;


@Slf4j
@EnableAsync
@EnableScheduling
@EnableFeignClients
@SpringBootApplication
public class GrpcClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(GrpcClientApplication.class, args);
    }


    @Bean
    @GrpcGlobalClientInterceptor
    public ClientInterceptor globalTokenClientInterceptor() {
        return new ClientInterceptor() {
            @Override
            public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> methodDescriptor,
                                                                       CallOptions callOptions,
                                                                       Channel channel) {
                var delegate = channel.newCall(methodDescriptor, callOptions);
                return new ForwardingClientCall.SimpleForwardingClientCall<>(delegate) {
                    @Override
                    public void start(Listener<RespT> responseListener, Metadata headers) {
                        final var tenantId = IdUtil.objectId();
                        log.info("address : {}  TenantId: {} ", methodDescriptor.getFullMethodName(), tenantId);
                        headers.put(GlobalConst.TENANT_ID, tenantId);
                        super.start(responseListener, headers);
                    }
                };
            }
        };
    }


}
